#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
#TODO: documentation!
"""


__version__ = '$Id$'


version = '0.1'


#---- imports ----#
import os
import sys
import logging
import logging.handlers

from bipy import engine

#---- rquirements ----#
def _requires_pyglet_version(version):
    try:
        import pyglet
        req = [int(i) for i in version if i in '1234567890']
        have = [int(i) for i in pyglet.version if i in '1234567890']
        if tuple(req) > tuple(have):
            raise ImportError('bipy requires pyglet %s or later' % version)
    except ImportError:
        raise ImportError('bipy requires pyglet %s or later' % version)
        
_requires_pyglet_version('1.0')




#---- logging ----#
#XXX: do we really need logging?
log_level = logging.DEBUG
log_path = os.path.join(os.path.expanduser('~'), '.bipy.log')

def _configure_log():
    global log_level
    global log_path
    print log_level, log_path
    logging.basicConfig(level=log_level, 
        format= '%(levelname)s {%(name)s} %(filename)s(%(lineno)d): %(message)s')
    # rotating file handler
    _log_handler = logging.handlers.RotatingFileHandler(log_path, mode='ab',\
        maxBytes=1024*1024, backupCount=10, encoding='utf8')
    _formatter = logging.Formatter( \
    '%(asctime)s %(levelname)s {%(name)s} %(filename)s(%(lineno)d): %(message)s', \
    '%a, %d %b %Y %H:%M:%S')
    _log_handler.setFormatter(_formatter)
    logging.getLogger().addHandler(_log_handler)
    # first log entry
    logging.getLogger('bipy').info('log configured(level: %d)' % log_level)

class _stream_splitter(object):
    def __init__(self, fileobj, stdstream):
        self._file = fileobj
        self._stream = stdstream

    def close(self):
        self._file.close()
        self._stream.close()

    def write(self, msg):
        self._file.write(msg)
        self._stream.write(msg)

    def flush(self):
        self._file.flush()
        self._stream.flush()

    def writelines(self, seq):
        self._file.writelines(seq)
        self._stream.writelines(seq)

# capture std streams to files
if log_level > logging.INFO:
    sys.stdout = file('stdout.log', 'wb')
    sys.stderr = file('stderr.log', 'wb')
else:
    sys.stderr = _stream_splitter(file('errors.log', 'wb'), sys.__stderr__)

#---- functions ----#

def init(config=None):
    pass
#    _configure_log()
#    raise NotImplementedError()
    pass

def run(scene):
    eng = engine.EngineClass()
    eng.run(scene(eng))

#----  ----#
#TODO: lazy module imports?